package com.kitten.gateway.filter;

import cn.dev33.satoken.stp.StpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @description: 确保 AddUserId2HeaderFilter 过滤器的执行顺序位于 SaReactorFilter 过滤器的后面，SaReactorFilter 的执行顺序值为 -100。
 */
@Slf4j
@Order(-90)
@Component
public class AddUserId2HeaderFilter implements GlobalFilter {
    /**
     * 传递用户ID到下一个过滤器
     */
    private static final String HEADER_USER_ID = "userId";


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("=============> TokenConvertFilter");
        Long userId = null;
        try {
            userId = StpUtil.getLoginIdAsLong();
            log.info("网关截取当前用户ID: {}", userId);
        } catch (Exception e) {
            return chain.filter(exchange);  // 未登录，不做处理, 本过滤器方向
        }
        Long finalUserId = userId;
        ServerWebExchange newExchange = exchange.mutate()
                .request(builder -> builder.header(HEADER_USER_ID, String.valueOf(finalUserId)))
                .build();
        return chain.filter(newExchange);
    }
}
